import { DatePicker } from '@/components/AntdProxy';
import Crud from '@/components/Crud';
import { DriverSelect, GroupTreeSelect } from '@/components/CustomForm';

import request from '@/utils/request';
import { DownloadOutlined } from '@ant-design/icons';
import { Button } from 'antd';
import dayjs from 'dayjs';
import { useRef, useState } from 'react';

const getList = async (params) => {
  const res = await request({
    url: '/datas/driver/salary/day/list',
    method: 'GET',
    custom: true,
    params: params,
  });
  return {
    total: res?.total,
    data: res?.data,
  };
};

const Index = (props) => {
  const { onDetail } = props;
  const crudRef = useRef();
  const [params, setParams] = useState();
  const getDynamicColumns = () => {
    console.log('params', params);
    if (params) {
      const { fromTime, toTime } = params;
      const days = dayjs(toTime).diff(dayjs(fromTime), 'day') + 1;
      const columns = [];
      for (let i = 0; i < days; i++) {
        const day = dayjs(fromTime).add(i, 'day');
        columns.push({
          title: day.format('D号'),
          width: 70,
          render: (text, record) => {
            return (
              record?.days?.find?.(
                (item) => item.day === day.format('YYYY-MM-DD'),
              )?.driverPrice || 0
            );
          },
        });
      }
      return columns;
    } else {
      return [];
    }
  };
  const columns = [
    {
      title: '序号',
      fixed: 'left',
      width: 65,
      render: (text, record, index) => index + 1,
    },
    {
      title: '组织',
      dataIndex: 'groupName',
      fixed: 'left',
      width: 220,
    },
    {
      title: '驾驶员',
      dataIndex: 'realname',
      fixed: 'left',
      width: 220,
      render: (text, record) => (
        <a
          title="点击查看明细"
          onClick={() => {
            const params = crudRef.current?.getParams();
            onDetail?.({
              driverId: record.driverId,
              fromTime: dayjs(params.fromTime).startOf('day'),
              toTime: dayjs(params.toTime).endOf('day'),
              uuid: dayjs().valueOf(),
              timeType: 0,
            });
          }}
        >
          {text}
        </a>
      ),
    },
    {
      title: '手机号',
      dataIndex: 'phone',
      width: 140,
    },
    {
      title: '趟次数',
      dataIndex: 'total',
      width: 100,
    },
    {
      title: '司机薪金(元)',
      dataIndex: 'driverPrice',
      width: 120,
    },
    {
      title: '每日薪金',
      children: getDynamicColumns(),
    },
    // 根据开始结束日期，动态创建列
    // ...getDynamicColumns(),
  ];

  const fields = [
    {
      label: '组织',
      name: 'groupId',
      children: <GroupTreeSelect placeholder="请选择组织" />,
    },
    {
      label: '驾驶员',
      name: 'driverId',
      children: <DriverSelect placeholder="请选择驾驶员" />,
    },
    {
      label: '开始时间',
      name: 'fromTime',
      children: (
        <DatePicker
          allowClear={false}
          placeholder="请选择开始时间"
          format="YYYY-MM-DD"
        />
      ),
    },
    {
      label: '结束时间',
      name: 'toTime',
      children: (
        <DatePicker
          allowClear={false}
          placeholder="请选择结束时间"
          format="YYYY-MM-DD"
        />
      ),
    },
  ];

  const handleExport = async () => {
    const params = crudRef.current?.getParams();
    const res = await request({
      url: '/datas/driver/salary/day/export/list',
      method: 'GET',
      params,
    });
    window.open(res);
  };

  return (
    <>
      <Crud
        ref={crudRef}
        rowKey="id"
        queryFormProps={{
          labelCol: 7,
          initialValues: {
            fromTime: dayjs().startOf('month'),
            toTime: dayjs().endOf('month'),
          },
        }}
        fields={fields}
        columns={columns}
        request={getList}
        onParamsChange={(_params) => setParams(_params)}
        transformParams={(params) => {
          return {
            ...params,
            fromTime: params?.fromTime?.format('YYYY-MM-DD'),
            toTime: params?.toTime?.format('YYYY-MM-DD'),
          };
        }}
        toolbar={
          <>
            <Button
              type="primary"
              icon={<DownloadOutlined />}
              onClick={handleExport}
            >
              导出
            </Button>
          </>
        }
      />
    </>
  );
};

export default Index;
